package com.itmk.config.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.itmk.context.UserContext;
import com.itmk.context.UserContextInfo;
import com.itmk.jwt.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 存储用户局部信息拦截器
 */
@Component
@Slf4j
public class UserInfoInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            token = request.getParameter("token");
        }
        if(StringUtils.isEmpty(token)){
           return true;
        }
        boolean expired = jwtUtils.verify(token);
        if(!expired){
          return true;
        }
        //设置user信息
        //验证token 获取userId
        String userId = jwtUtils.jwtDecode(token).getClaim("userId").asString();
        log.info("登录用户ID:{}",userId);
        //设置用户信息
        UserContextInfo userContext = new UserContextInfo();
        userContext.setUserId(Long.valueOf(userId));
        UserContext.setUser(userContext);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户信息
        UserContext.removeUser();
    }
}
